﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;

public partial class Account_Login : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.IsAuthenticated)
        {
            Response.Redirect("~/Default.aspx");
        }
        else
        {
            RegisterHyperLink.NavigateUrl = "Register.aspx?ReturnUrl=" + HttpUtility.UrlEncode(Request.QueryString["ReturnUrl"]);
        }
    }
    protected void LoginButton_Click(object sender, EventArgs e)
    {
        if (LoginUser.UserName == "" || LoginUser.Password == "")
        {
            return;
        }
        else { 
            ManageDatabase data = new ManageDatabase();
            String userId = data.AuthenticateUser(LoginUser.UserName, LoginUser.Password);

            if (userId != "" && userId != null)
            {
                HttpCookie authCookie = FormsAuthentication.GetAuthCookie(LoginUser.UserName, true);
                FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authCookie.Value);
                FormsAuthenticationTicket newTicket = new FormsAuthenticationTicket(ticket.Version, ticket.Name, ticket.IssueDate, ticket.Expiration, ticket.IsPersistent, userId);
                authCookie.Value = FormsAuthentication.Encrypt(newTicket);
                Response.Cookies.Add(authCookie);

                String redirectUrl = FormsAuthentication.GetRedirectUrl(LoginUser.UserName, true);
                Response.Redirect(redirectUrl);
            }
            else {
                Response.Redirect("~/Account/Login.aspx");
            }
        }
    }
}
